import { getUserInfoAPI, loginAPI } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  // 1、从本地获取token，防止刷新token丢失
  token: getToken(),
  mobile: '13800000002',
  password: 'hm#qd@23!',
  userInfo: {},
  // 2、定义路由数据
  routes: constantRoutes
}
// 负责计算类的逻辑
const mutations = {
  setRoutes(state, payload) {
    state.routes = [...constantRoutes, ...payload]
  },
  // 2、定义保存token到state的方法
  saveToken(state, payload) {
    state.token = payload
  },
  deleteToken(state) {
    state.token = null
  },
  changeUserInfo(state, payload) {
    state.mobile = payload.mobile
    state.password = payload.password
  },
  saveUserInfo(state, payload) {
    state.userInfo = payload
  }
}

const actions = {
  async loginAction(store, payload) {
    // action 调用api CORS报错
    const res = await loginAPI(payload)

    // 3、提交修改数据到mutations
    store.commit('saveToken', res)

    // 4、持久化存储token
    setToken(res)

    // 3.跳转到首页
    router.push('/')
    // 5.提示用户
    Message({ message: '登录成功', type: 'success' })
  },
  // 定义删除token的方法
  async logout(store) {
    store.commit('deleteToken')// 清除vuex的token
    store.commit('saveUserInfo', {})// 清除vuex中的用户信息
    removeToken()// 清除cookie的token
    router.push('/login') // 跳转到登录
    // 退出登录需要重置路由
    resetRouter()
  },
  async getUserInfoAction(store) {
    const res = await getUserInfoAPI()
    store.commit('saveUserInfo', res)
    return res // 返回数据
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

